
package com.dd.keel.core.database;

import java.sql.Connection;
import java.util.Map;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.dd.keel.core.database.jta.StandardXAPoolDataSourceEx;

/**
 * 支持事务的DBManager实现
 * @author Kevin.XU
 *
 */
public class XADatabaseService implements DBManager, ApplicationContextAware {

	final static private Logger LOGGER = LoggerFactory.getLogger(XADatabaseService.class);
	
	private ApplicationContext applicationContext;
	
	private Map<String, StandardXAPoolDataSourceEx> beans;
	/**
	 * 
	 */
	public XADatabaseService() {
	}

	/* (non-Javadoc)
	 * @see com.ailk.aiip.interfaces.db.DBManager#getConnection(java.lang.String)
	 */
	public Connection getConnection(String key) throws Exception {
		return getBeans().get(key).getConnection();
	}

	/* (non-Javadoc)
	 * @see com.ailk.aiip.interfaces.db.DBManager#getDataSource(java.lang.String)
	 */
	public DataSource getDataSource(String key) throws Exception {
		StandardXAPoolDataSourceEx poolds = getBeans().get(key);
		LOGGER.debug("@@current connection pool : total = {}, used = {}, idle = {}", new Object[]{poolds.pool.getCount(), poolds.pool.getLockedObjectCount(), poolds.pool.getUnlockedObjectCount()});
		return poolds;
	}

	/**
	 * 所有xa pool datasource实例
	 * @return the beans
	 */
	private Map<String, StandardXAPoolDataSourceEx> getBeans() {
		if (beans == null) {
			beans = getApplicationContext().getBeansOfType(StandardXAPoolDataSourceEx.class);
		}
		return beans;
	}

	/**
	 * @return the applicationContext
	 */
	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/*
	 * (non-Javadoc)
	 * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}

}
